package org.cn.lennon.mybatis.executors.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.cn.lennon.mybatis.config.MapperStatment;
import org.cn.lennon.mybatis.executors.Executors;
import org.cn.lennon.mybatis.executors.impl.handler.PreparedStatmentHandler;
import org.cn.lennon.mybatis.transcation.impl.connection.ConnestionPool;

public class CacheExecutors implements Executors {

	// 注入一个执行器
	private Executors executors;

	// 作为一级缓存使用
	private Map<String, Object> localCache = new HashMap();

	public CacheExecutors(Executors executors) {
		this.executors = executors;
	}

	public <T> T query(MapperStatment mapperStatemnt, Object queryObject) throws SQLException {
		return query(mapperStatemnt, new Object[] { queryObject });
	}

	public <T> T query(MapperStatment mapperStatemnt, Object[] queryObjects) throws SQLException {
		Object resultObject = localCache.get(mapperStatemnt.getId());
		if (resultObject != null) {
			return (T) resultObject;
		}
		resultObject = executors.query(mapperStatemnt, queryObjects);
		localCache.put(mapperStatemnt.getId(), resultObject);
		return (T) resultObject;
	}

	public void commit() throws SQLException {
		executors.commit();
	}

	public void rollback() throws SQLException {
		executors.rollback();
	}

	public void close() throws SQLException {
		executors.close();
	}

	public int update(MapperStatment mapperStatemnt, Object[] queryObjects) throws SQLException {
		return executors.update(mapperStatemnt, queryObjects);
	}

	public int insert(MapperStatment mapperStatemnt, Object[] queryObjects) throws SQLException {
		return executors.insert(mapperStatemnt, queryObjects);
	}

	public int delete(MapperStatment mapperStatemnt, Object[] queryObjects) throws SQLException {
		return executors.insert(mapperStatemnt, queryObjects);
	}
}
